package io;

import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
/**
 * IO体系标准的异常处理方式
 *  try...catch...finally
 */
public class IODemo {
    public static void main(String[] args) {
        //1.利用FileReader关联源文件
        FileReader fr = null;
        FileWriter fw = null;

        try {
            fr = new FileReader("day23-IO-02/src/reader/FileReaderDemo01.java");
            //2.利用FileWriter关联目的文件
            fw = new FileWriter("day23-IO-02/copy02.txt");

            //3.先将数据批量读取到字符数组中,然后再将字符数组中的内容写入目的文件中
            char[] chars = new char[1024];//一般声明1024整数倍
            int length;

            while ((length = fr.read(chars)) != -1) {
                fw.write(chars, 0, length);
            }
        } catch (FileNotFoundException e) {
            System.out.println("文件没找到:" + e.getMessage());
            e.printStackTrace();
        }catch (IOException e){
            System.out.println("文件读写异常:" + e.getMessage());
            e.printStackTrace();
        }finally {
            //4.无论try中的代码是否抛异常,我们都要关流释放资源
            if (fr!=null) {//避免fr = null,调用close方法时产生空指针异常
                try {
                    fr.close();
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
            if (fw!=null) {
                try {
                    fw.close();
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
        }
    }
}
